package mysql

import (
	"context"
	"errors"
	"go.uber.org/zap"
	"golang-sgg-daijia/internal/model"
	"gorm.io/gorm"
)

type DriverAccountDetailDao interface {
	Create(ctx context.Context, driverAccountDetail *model.DriverAccountDetail) error
	GetByTradeNo(ctx context.Context, orderNo string) (*model.DriverAccountDetail, error)
}

func NewDriverAccountDetailDao(
	r *MysqlClient,
) DriverAccountDetailDao {
	return &driverAccountDetailDao{
		MysqlClient: r,
	}
}

type driverAccountDetailDao struct {
	*MysqlClient
}

func (r *driverAccountDetailDao) Create(ctx context.Context, driverAccountDetail *model.DriverAccountDetail) error {
	if err := r.DB(ctx).Create(driverAccountDetail).Error; err != nil {
		r.logger.WithContext(ctx).Error("driverAccountDetailDao|Create(", zap.Any("data", map[string]interface{}{
			"driverSet": *driverAccountDetail,
		}), zap.Error(err))
		return err
	}
	return nil
}

func (r *driverAccountDetailDao) GetByTradeNo(ctx context.Context, orderNo string) (*model.DriverAccountDetail, error) {
	driverAccountDetail := &model.DriverAccountDetail{}
	if err := r.DB(ctx).Where("trade_no = ?", orderNo).Where("is_deleted", 0).First(driverAccountDetail).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		r.logger.WithContext(ctx).Error("driverAccountDetailDao|GetByTradeNo", zap.Error(err))
		return nil, err
	}
	return driverAccountDetail, nil
}